package com.blogsystem.service.impl;

import com.blogsystem.entity.ClickCount;
import com.blogsystem.entity.Article;
import com.blogsystem.mapper.ClickCountMapper;
import com.blogsystem.service.ClickCountService;
import com.blogsystem.service.ArticleService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ClickCountServiceImpl extends ServiceImpl<ClickCountMapper, ClickCount> implements ClickCountService {

    @Autowired
    private ArticleService articleService;


    /**
     * 总点击量统计逻辑：
     * 1. 根据用户ID从Article表中查询所有属于该用户的文章
     * 2. 提取文章ID列表
     * 3. 使用articleIds在ClickCount表中查询对应的所有点击量数据
     * 4. 对查询到的点击量进行求和计算
     *
     * 日志输出说明：
     * - 打印用户关联的文章ID列表用于调试验证
     * - 打印最终统计的总点击量用于结果确认
     */

    @Override
    public long getUserTotalClicks(Integer userId) {

        
        // 获取用户的所有文章ID
        List<Article> userArticles = articleService.list(new QueryWrapper<Article>().eq("user_id", userId));
        
        if (userArticles.isEmpty()) {
            return 0;
        }
        
        List<Integer> articleIds = userArticles.stream()
                                              .map(Article::getArticleId)
                                              .collect(Collectors.toList());
        
        // 查询这些文章的总点击量
        long totalClicks = baseMapper.selectList(new QueryWrapper<ClickCount>().in("article_id", articleIds))
                                    .stream()
                                    .mapToLong(ClickCount::getTotalClicks)
                                    .sum();
        
        // 调试日志输出
        System.out.println("用户 " + userId + " 的文章 IDs: " + articleIds);
        System.out.println("查询到的点击量总和: " + totalClicks);
        
        return totalClicks;
    }
}